<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ShoppingCart, Search, Delete, ArrowRight, Star, StarFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { cartGetItemService } from '@/api/cart';

const router = useRouter();

onMounted(() => {
  document.documentElement.classList.remove('dark');
})
onUnmounted(() => {
  document.documentElement.classList.add('dark');
})

// 购物车数据
const cartItems = ref([
])

const getCartItems = async () => {
  const res = await cartGetItemService();
  const cartItemList = res.data.data;

  // 数据格式转换
  for (const cartItem of cartItemList) {
    const sku = JSON.parse(cartItem.selectedSku);
    const skuValueList = Object.values(sku);
    cartItem.selectedSku = skuValueList.join(',');
  }

  cartItems.value.push(...cartItemList);
}
getCartItems();

// 搜索相关状态
const searchQuery = ref('')
const loadingSearch = ref(false)

// 全选状态
const selectAll = ref(false)

// 计算总金额
const totalAmount = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((sum, item) => sum + (item.price * item.quantity), 0)
    .toFixed(2)
})

// 计算选中商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 计算节省金额 - 基于原始价格计算
const savedAmount = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((sum, item) => sum + ((item.price - item.currentPrice) * item.quantity), 0)
    .toFixed(2)
})

// 全选/取消全选
const toggleSelectAll = () => {
  cartItems.value.forEach(item => {
    item.selected = selectAll.value
  })
}

// 单个商品选择状态变化
const handleSelectChange = () => {
  selectAll.value = cartItems.value.length > 0 && 
                    cartItems.value.every(item => item.selected)
}

// 删除购物车商品
const removeItem = (item) => {
  ElMessageBox.confirm(`确定要删除${item.name}吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cartItems.value = cartItems.value.filter(i => i.id !== item.id)
    ElMessage.success('已删除商品')
  })
}

// 删除选中商品
const removeSelected = () => {
  if (selectedCount.value === 0) {
    ElMessage.warning('请先选择商品')
    return
  }
  
  ElMessageBox.confirm('确定要删除选中的商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cartItems.value = cartItems.value.filter(item => !item.selected)
    selectAll.value = false
    ElMessage.success('已删除选中商品')
  })
}

// 远程搜索商品（在购物车中搜索）
const remoteSearch = () => {
  loadingSearch.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    loadingSearch.value = false
  }, 800)
}

// 获取当前显示的购物车商品（根据搜索条件过滤）
const displayedCartItems = computed(() => {
  if (!searchQuery.value.trim()) {
    return cartItems.value
  }
  
  const query = searchQuery.value.toLowerCase()
  return cartItems.value.filter(item => 
    item.name.toLowerCase().includes(query) || 
    item.merchant.toLowerCase().includes(query) ||
    item.specs.toLowerCase().includes(query)
  )
})

// 去结算
const checkout = () => {
  if (selectedCount.value === 0) {
    ElMessage.warning('请先选择要购买的商品')
    return
  }
  
  ElMessage.success(`已选择${selectedCount.value}件商品，总金额¥${totalAmount.value}`)
}

</script>

<template>
  <div class="cart-container">
    <!-- 头部 -->
    <div class="cart-header">
      <div class="header-content">
        <div class="header-left">
          <el-icon :size="28" color="#409EFF" @click="router.back()"><ShoppingCart /></el-icon>
          <h1>我的购物车</h1>
          <span class="count-badge">{{ cartItems.length }} 件商品</span>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="在购物车中搜索商品..."
          clearable
          @input="remoteSearch"
          :loading="loadingSearch"
          size="large"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button type="primary" :icon="Search">搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 购物车主体 -->
    <div class="cart-main">
      <!-- 购物车商品列表 -->
      <div class="cart-items">
        <div class="cart-toolbar">
          <el-checkbox v-model="selectAll" @change="toggleSelectAll">全选</el-checkbox>
          <el-button type="danger" :icon="Delete" @click="removeSelected" :disabled="selectedCount === 0">
            删除选中
          </el-button>
        </div>

        <div v-if="displayedCartItems.length === 0" class="empty-cart">
          <div class="empty-content">
            <img src="https://cdn-icons-png.flaticon.com/512/2037/2037457.png" alt="空购物车">
            <p v-if="searchQuery">没有找到匹配的商品</p>
            <p v-else>您的购物车是空的</p>
            <el-button type="primary" @click="router.push('/marketplace')">去逛逛</el-button>
          </div>
        </div>

        <div v-for="item in displayedCartItems" :key="item.id" class="cart-item">
          <div class="item-left">
            <el-checkbox v-model="item.selected" @change="handleSelectChange"></el-checkbox>
            <div class="item-image">
              <img :src="item.coverUrl" :alt="item.productTitle">
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.productTitle }}</div>
              <div class="item-specs">{{ item.selectedSku }}</div>
              <div class="item-merchant">
                <span>{{ item.merchantName }}</span>
                <div class="rating">
                  <el-icon v-for="i in 5" :key="i" :color="i <= Math.floor(item.rating) ? '#ff9900' : '#dcdfe6'">
                    <StarFilled v-if="i <= Math.floor(item.rating)" />
                    <Star v-else />
                  </el-icon>
                  <span class="rating-value">{{ item.rating }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="item-right">
            <!-- 价格显示区域修改 - 添加原始价格 -->
            <div class="item-price">
              <div class="current-price">¥{{ item.currentPrice.toFixed(2) }}</div>
              <div :class="(item.currentPrice >= item.price) ? 'original-price' : 'original-price-expensive'">¥{{ item.price.toFixed(2) }}</div>
              <div class="saving-percent" v-if="((1 - item.currentPrice / item.price) * 100).toFixed(0) > 0">
                省{{ ((1 - item.currentPrice / item.price) * 100).toFixed(0) }}%
              </div>
            </div>
            
            <div class="item-quantity">
              <el-input-number 
                v-model="item.quantity" 
                :min="1" 
                :max="item.stock"
                size="small"
                controls-position="right"
              />
              <div class="stock-info">库存: {{ item.stock }}</div>
            </div>
            
            <div class="item-actions">
              <el-button type="danger" :icon="Delete" circle @click="removeItem(item)" />
            </div>
          </div>
        </div>
      </div>

      <!-- 结算区域 -->
      <div class="checkout-section">
        <div class="checkout-container">
          <div class="checkout-info">
            <div class="selected-count">
              已选 <span class="highlight">{{ selectedCount }}</span> 件商品
            </div>
            <div class="saved-amount" v-show="savedAmount > 0">
              已节省: <span class="highlight">¥{{ savedAmount }}</span>
            </div>
            <div class="total-amount">
              总计: <span class="highlight">¥{{ totalAmount }}</span>
            </div>
          </div>
          
          <div class="checkout-button">
            <el-button type="primary" @click="checkout">
              去结算 <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 为您推荐 -->
    <div class="recommend-section">
      <h2>为您推荐</h2>
      <div class="recommend-list">
        <div class="recommend-item">
          <div class="recommend-image">
            <img src="https://images.unsplash.com/photo-1607853554439-0069ec0f29b9?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8c21hcnRwaG9uZXxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=500&q=60" alt="推荐商品">
          </div>
          <div class="recommend-name">iPhone 14 Pro Max</div>
          <div class="recommend-price">¥8999</div>
        </div>
        <div class="recommend-item">
          <div class="recommend-image">
            <img src="https://images.unsplash.com/photo-1546868871-7041f2a55e12?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8d2F0Y2h8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60" alt="推荐商品">
          </div>
          <div class="recommend-name">Apple Watch Ultra</div>
          <div class="recommend-price">¥6299</div>
        </div>
        <div class="recommend-item">
          <div class="recommend-image">
            <img src="https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Y2FtZXJhfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60" alt="推荐商品">
          </div>
          <div class="recommend-name">Sony A7 IV</div>
          <div class="recommend-price">¥16999</div>
        </div>
        <div class="recommend-item">
          <div class="recommend-image">
            <img src="https://images.unsplash.com/photo-1572569511254-d8f925fe2cbb?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Z2FtaW5nJTIwa2V5Ym9hcmR8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60" alt="推荐商品">
          </div>
          <div class="recommend-name">机械键盘</div>
          <div class="recommend-price">¥699</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
  background: #f8f9fa;
}

.cart-header {
  background: linear-gradient(135deg, #1a73e8, #0d47a1);
  color: white;
  padding: 20px 0;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .el-icon {
        cursor: pointer;
      }

      h1 {
        font-size: 24px;
        font-weight: 700;
        margin: 0;
        color: white;
      }
      
      .count-badge {
        background: rgba(255, 255, 255, 0.2);
        padding: 4px 12px;
        border-radius: 16px;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
}

.search-section {
  padding: 24px 0;
  margin-top: 20px;
  
  .search-container {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    padding: 24px;
    
    .el-input {
      border-radius: 50px;
      overflow: hidden;
      
      :deep(.el-input__wrapper) {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        border-radius: 50px;
        padding: 0 20px;
        height: 56px;
      }
      
      :deep(.el-input-group__append) {
        background: #1a73e8;
        border: none;
        border-radius: 0 50px 50px 0;
        padding: 0 28px;
        box-shadow: none;
        
        .el-button {
          color: white;
          font-weight: 600;
          
          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }
        }
      }
    }
    
  }
}

.cart-main {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 40px;
}

.cart-items {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  .cart-toolbar {
    display: flex;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #f0f2f7;
    background: #f9fafc;
    
    .el-checkbox {
      margin-right: 20px;
      font-weight: 500;
    }
  }
  
  .empty-cart {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 300px;
    
    .empty-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      
      img {
        width: 120px;
        height: 120px;
        opacity: 0.6;
        margin-bottom: 20px;
      }
      
      p {
        color: #666;
        font-size: 16px;
        margin-bottom: 24px;
      }
    }
  }
  
  .cart-item {
    display: flex;
    justify-content: space-between;
    padding: 24px;
    border-bottom: 1px solid #f0f2f7;
    transition: background 0.2s;
    
    &:hover {
      background: #fafbfd;
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-left {
      display: flex;
      align-items: center;
      flex: 1;
      
      .el-checkbox {
        margin-right: 20px;
      }
      
      .item-image {
        width: 120px;
        height: 120px;
        border-radius: 12px;
        overflow: hidden;
        margin-right: 24px;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .item-info {
        .item-name {
          font-size: 16px;
          font-weight: 600;
          margin-bottom: 8px;
          color: #1a1a1a;
        }
        
        .item-specs {
          background: #f5f7fa;
          padding: 4px 10px;
          border-radius: 4px;
          color: #606266;
          font-size: 14px;
          display: inline-block;
          margin-bottom: 12px;
        }
        
        .item-merchant {
          color: #606266;
          font-size: 14px;
          display: flex;
          align-items: center;
          gap: 8px;
          
          .rating {
            display: flex;
            align-items: center;
            gap: 2px;
            
            .rating-value {
              margin-left: 4px;
              font-weight: 600;
              color: #ff9900;
            }
          }
        }
      }
    }
    
    .item-right {
      display: flex;
      align-items: center;
      gap: 30px;
      
      /* 价格区域样式修改 */
      .item-price {
        width: 120px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .current-price {
          font-weight: 700;
          color: #ff5000;
          font-size: 18px;
        }
        
        .original-price-expensive {
          font-size: 14px;
          color: #999;
          text-decoration: line-through;
          margin-top: 4px;
        }

        .original-price {
          font-size: 14px;
          color: #999;
          margin-top: 4px;
        }
        
        .saving-percent {
          background: #ff5000;
          color: white;
          font-size: 12px;
          padding: 2px 6px;
          border-radius: 10px;
          margin-top: 4px;
        }
      }
      
      .item-quantity {
        width: 140px;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        
        .stock-info {
          font-size: 12px;
          color: #909399;
        }
      }
      .item-actions {
        width: 60px;
        display: flex;
        justify-content: center;
      }
    }
  }
}

.checkout-section {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  padding: 24px;
  
  .checkout-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .checkout-info {
      display: flex;
      gap: 40px;
      align-items: center;
      
      .selected-count, .total-amount, .saved-amount {
        font-size: 16px;
        color: #606266;
        
        .highlight {
          font-weight: 700;
          color: #ff5000;
          font-size: 20px;
          margin-left: 4px;
        }
      }
      
      .total-amount .highlight {
        font-size: 24px;
      }
      
      .saved-amount {
        color: #67c23a;
        
        .highlight {
          color: #67c23a;
        }
      }
    }
    
    .checkout-button {
      .el-button {
        height: 56px;
        padding: 0 48px;
        font-size: 18px;
        font-weight: 600;
        border-radius: 50px;
        background: linear-gradient(135deg, #ff6a00, #ff5000);
        border: none;
        box-shadow: 0 4px 12px rgba(255, 106, 0, 0.3);
        
        &:hover {
          opacity: 0.9;
          transform: translateY(-2px);
          box-shadow: 0 6px 16px rgba(255, 106, 0, 0.4);
        }
        
        .el-icon {
          margin-left: 8px;
        }
      }
    }
  }
}

.recommend-section {
  margin-top: 40px;
  
  h2 {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 20px;
    padding-left: 14px;
    position: relative;
    color: #1a1a1a;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 5px;
      height: 20px;
      width: 4px;
      background: #1a73e8;
      border-radius: 2px;
    }
  }
  
  .recommend-list {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    
    .recommend-item {
      background: white;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      transition: transform 0.3s, box-shadow 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }
      
      .recommend-image {
        height: 180px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f9fa;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .recommend-name {
        padding: 16px 16px 8px;
        font-weight: 500;
        font-size: 15px;
        color: #1a1a1a;
      }
      
      .recommend-price {
        padding: 0 16px 16px;
        color: #ff5000;
        font-weight: 700;
        font-size: 18px;
      }
    }
  }
}

@media (max-width: 992px) {
  .cart-item {
    flex-direction: column;
    gap: 20px;
    
    .item-right {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .checkout-container {
    flex-direction: column;
    gap: 20px;
    align-items: flex-end !important;
  }
  
  .checkout-info {
    width: 100%;
    justify-content: space-between !important;
  }
  
  .recommend-list {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}

@media (max-width: 768px) {
  .item-left {
    flex-direction: column;
    align-items: flex-start !important;
    
    .item-image {
      margin-top: 16px;
      margin-right: 0 !important;
    }
  }
  
  .checkout-info {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 12px !important;
  }
  
  .recommend-list {
    grid-template-columns: repeat(1, 1fr) !important;
  }
}
</style>